package customerEnter.Frame.JDBCDao.daoFrame;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.jdbc.support.rowset.SqlRowSet;

import com.alibaba.fastjson.JSON;

import customerEnter.Frame.DaoDataTransmission.DaoFramUpdateOrAddMap;
import customerEnter.Frame.DaoDataTransmission.DaoFrameDMLBaseTransmission;
import customerEnter.Frame.DaoDataTransmission.DaoFramePameTransmission;
import customerEnter.Frame.DaoDataTransmission.PagingParametersResult;
import customerEnter.Frame.Enum.DataSourceControllerEnum;
import customerEnter.Frame.JDBCDao.EasyBuyDB;
import customerEnter.Frame.JDBCDao.Interface.DaoFrameIntermediateLayerInterface;
import customerEnter.Frame.JDBCDao.Interface.DaoFrameUseTypeInterface;
import customerEnter.Frame.JDBCDao.JdbcTemplate.RandomDataSource;
import customerEnter.Frame.JDBCDao.UseQuery.DaoFrameUseTypeListTImpl;
import customerEnter.Frame.JDBCDao.UseQuery.DaoFrameUseTypeMapImpl;
import customerEnter.Frame.JDBCDao.UseQuery.DaoFrameUseTypeStringImpl;
import customerEnter.Frame.JDBCDao.UseQuery.DaoFrameUseTypeStringsImpl;
import customerEnter.Frame.JDBCDao.UseQuery.DaoFrameUseTypeintImpl;
import customerEnter.Frame.JDBCDao.util.DaoFrameUtil;
import customerEnter.Frame.Utils.Log4j;
import customerEnter.Frame.Utils.SystemMD5;
import customerEnter.Frame.Utils.javaReflexClass;
import customerEnter.tool.WhetherToEmpty;

/**
 * 數據查詢的基類 框架的一層助手類
 * 
 * 类名称：DaoFrameTransmission 类描述： 创建人：dy 创建时间：2016-3-28 上午8:56:38
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class DaoFrameMiddleware<T, K> extends DaoFramMiddlAssistant<T, K> implements
		DaoFrameIntermediateLayerInterface<T, K> {

	/**
	 * 批量增加 獲取sql語句 單個
	 */
	public String SqlInsertBacth(String DataBase, String TableName, Class<?> class1) {
		Field[] find = class1.getDeclaredFields();
		String prope = "";
		String position = "";
		for (Field field : find) {
			String name = field.getName();
			if ("serialVersionUID".equals(name)) {
				continue;
			}
			if ("id".equals(name)) {
				continue;
			}
			if (WhetherToEmpty.StringWhetherToEmpty(prope)) {
				prope += "" + name + " ";
				position += "? ";
			} else {
				prope += "," + name + " ";
				position += ",? ";
			}
		}
		String sql = DataBase + " " + " insert into " + TableName + "(" + prope + ")" + " values(" + position + ")";
		return sql;
	}

	/**
	 * 獲取Result的結果集
	 */
	public SqlRowSet FindResultSetSql(DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		return setResultQuery(daoFramePameTransmission);
	}

	/**
	 * 判斷執行成不成功 true 成功 false 不成功
	 */
	private Boolean WhileQuerySql(String type, DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		Boolean boolean1 = true;
		if (type.equals("PreparedStatement"))
			/**
			 * 執行語句
			 */
			try {
				Log4j.Log4jOutInfo(daoFramePameTransmission.SQL);
				daoFramePameTransmission.sqlRowSet = EasyBuyDB.getJdbcTemplate().queryForRowSet(
						daoFramePameTransmission.SQL);
			} catch (Exception e) {
				String mString = "";
				if (RandomDataSource.DataSourceController == 0) {
					RandomDataSource.setDataSourceController(DataSourceControllerEnum.Controller_DataSource_1);
					boolean1 = true;// 等於false 再次執行本方法
					mString = "切換數據源" + RandomDataSource.DataSourceController;
				} else if (RandomDataSource.DataSourceController == 1) {
					boolean1 = true;// 等於true 繼續往下執行
					mString = " 語法錯誤";
				}
				Log4j.Log4jOutInfo("執行失敗 ：" + e.getMessage() + "_______" + mString);
			}
		return boolean1;
	}

	/**
	 * 功能： 判斷緩存有沒有 緩存存活3分鐘 用json sql語句為key 保證同一條sql語句 3分鐘內只訪問一次數據庫 包括沒緩存的時候查詢數據庫
	 */
	public void IfEhcache(DaoFrameDMLBaseTransmission daoFrameDMLBaseTransmission,
			DaoFramePameTransmission<T, K> daoFramePameTransmission) {

		DaoFrameUtil.ManageDaoFramePameTransmission(daoFrameDMLBaseTransmission, daoFramePameTransmission);
		if (daoFrameDMLBaseTransmission.isIfEhcache()) {
			try {

				// 判斷緩存中 有沒有數據
				if (!ifCache(SystemMD5.EnteMD5(daoFramePameTransmission.SQL), daoFramePameTransmission)) {
					setFindConditionQueryTo(daoFramePameTransmission);
				} else {
					Log4j.Log4jOutInfo("--------------------查詢緩存-------------------");

					PagingParametersResult pagingParametersResult = getPagingParametersResultCache(SystemMD5
							.EnteMD5(daoFramePameTransmission.SQL));

					daoFramePameTransmission.getPagingParametersResult().setpObject(
							JSON.toJavaObject(JSON.parseObject(pagingParametersResult.getpObject().toString()),
									daoFramePameTransmission.getFrameDataQueryUse().getValue()));

					daoFramePameTransmission.setPagingParametersResult(pagingParametersResult);
					/* JSON.toJSON(pagingParametersResult); */
					// if
					// (!WhetherToEmpty.ObjectWhetherToEmpty(pagingParametersResult))
					// {
					// List<?> list =
					// JSON.parseArray(pagingParametersResult.getPagingParametersList().toString(),
					// daoFrameDMLBaseTransmission.getClassName());
					// pagingParametersResult.setPagingParametersList(list);
					// daoFramePameTransmission.setPagingParametersResult(pagingParametersResult);
					// }
				}

			} catch (Exception e) {
				Log4j.Log4jOutInfo("-----------------------------------缓存系统服务没有打开-----------------------");
				Log4j.Log4jOutInfo("-----------------------------------查询数据库-----------------------");
				setFindConditionQueryTo(daoFramePameTransmission);
			}
		} else {
			Log4j.Log4jOutInfo("进入无缓存方法：。。。。。。。。。");
			setFindConditionQueryTo(daoFramePameTransmission);
		}
	}

	/**
	 * 跳轉到 查詢數據庫 並且設置緩存方法
	 */
	private void setFindConditionQueryTo(DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		Log4j.Log4jOutInfo("-----------------------------------查询数据库-----------------------");
		setfindConditionQuery(daoFramePameTransmission);
		SetEachAddParameter(daoFramePameTransmission);
	}

	/**
	 * 增加方法
	 */
	public void setInsertSql(DaoFramePameTransmission<T, K> daoFramePameTransmission, String DataBase,
			String TableName, LinkedList<?> values) {
		StringBuffer cen = new StringBuffer();
		WhileLinkedList(values, cen);
		daoFramePameTransmission.SQL = DaoFrameUtil.SqlManage(DataBase, " insert ", "", "into", TableName, "values("
				+ cen + " ) ");
	}

	/**
	 * 增加數據的方法
	 * 
	 * @throws ReflectiveOperationException
	 * @throws IllegalArgumentException
	 */
	public void setInsertMappingSql(DaoFramePameTransmission<T, K> daoFramePameTransmission, String DataBase,
			String TableName, Object t) throws Exception {

		DaoFramUpdateOrAddMap daoFramUpdateOrAddMap = javaReflexClass.getObjectNamesAndValuesAdd(t);
		String fieldNames = "";
		String values = "";
		for (Entry<String, Object> entry : daoFramUpdateOrAddMap.getData().entrySet()) {
			if (!WhetherToEmpty.StringWhetherToEmpty(fieldNames)) {
				fieldNames += ",";
				values += ",";
			}
			fieldNames += entry.getKey();
			values += entry.getValue();
		}
		daoFramePameTransmission.SQL = DaoFrameUtil.SqlManage(DataBase, " insert ", "", "into", TableName + "("
				+ fieldNames + ")", "values(" + values + " ) ");
	}

	/**
	 * 修改數據的方法
	 * 
	 * @throws ReflectiveOperationException
	 * @throws IllegalArgumentException
	 */
	public void setUpdateMappingSql(DaoFramePameTransmission<T, K> daoFramePameTransmission, String DataBase,
			String TableName, Object t, String where) throws Exception {
		String string = "";// 獲取全部屬性的類
		DaoFramUpdateOrAddMap daoFramUpdateOrAddMap = javaReflexClass.getObjectNamesAndValuesUpdate(t);
		for (Entry<String, Object> entry : daoFramUpdateOrAddMap.getData().entrySet()) {
			if (!WhetherToEmpty.StringWhetherToEmpty(string)) {
				string += ",";
			}
			string += entry.getKey() + "=" + entry.getValue();
		}
		daoFramePameTransmission.SQL = DaoFrameUtil.SqlManage(DataBase, " update ", TableName, " set ", string,
				" where 1=1  " + where);
	}

	public String IfSqlError(DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		Integer integer = 0;
		String error = ":null";
		try {
			integer = setInsertExec(daoFramePameTransmission);
		} catch (Exception e) {
			Log4j.Log4JOutError(e.getMessage());
			integer = 0;
			error = e.getMessage();
		}
		return integer > 0 ? "success:" + integer + " 条數據執行成功" : "fiel" + error;
	}

	public SqlRowSet setResultQuery(DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		Boolean boolean1 = false;
		while (!boolean1) {
			boolean1 = WhileQuerySql(daoFramePameTransmission.SqltatementType, daoFramePameTransmission);
		}
		return daoFramePameTransmission.sqlRowSet;

	}

	/**
	 * 設置查找數據庫 單個rs 結果
	 * 
	 */
	public void setfindConditionQuery(DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		setResult(daoFramePameTransmission);
	}

	/**
	 * 獲取泛型的名字
	 */
	public String getClassName(T t) {
		String string = "";
		try {
			String tName = t.getClass().getName().toString();
			String[] tnames = tName.split("@");
			String tName1 = tnames[0];
			String[] tName1s = tName1.split("\\.");
			string = tName1s[tName1s.length - 1];
		} catch (Exception e) {
			Log4j.Log4JOutError(e.getMessage());
		}
		return string;
	}

	/**
	 * 獲取類型的名字
	 */
	public String getClassName(Class<?> class1) {
		String ClassName = "admin";
		try {
			String tName = class1.getName().toString();
			String[] tnames = tName.split("@");
			String tName1 = tnames[0];
			String[] tName1s = tName1.split("\\.");
			ClassName = tName1s[tName1s.length - 1];
		} catch (Exception e) {
			Log4j.Log4JOutError(e.getMessage());
		}
		return ClassName;
	}

	/**
	 * 封裝rs
	 */
	public void setResult(DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		FindResultSetSql(daoFramePameTransmission);
		Object object = userQueryType(getDaoFrameUseTypeInterface(daoFramePameTransmission.getFrameDataQueryUse()
				.getValue()), daoFramePameTransmission);

		daoFramePameTransmission.getPagingParametersResult().setpObject(object);
	}

	public <Y> Y userQueryType(DaoFrameUseTypeInterface daoFrameUseTypeInterface,
			DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		return (Y) daoFrameUseTypeInterface.useDaoFrameDataType(daoFramePameTransmission);
	}

	public DaoFrameUseTypeInterface getDaoFrameUseTypeInterface(Class<?> class1) {
		return getDaoFrameUseTypeInterface(class1.getName());
	}

	Map<String, DaoFrameUseTypeInterface>	map	= new HashMap<String, DaoFrameUseTypeInterface>();

	public DaoFrameUseTypeInterface getDaoFrameUseTypeInterface(String string) {
		if (map.size() <= 0) {
			map.put(Collection.class.getName(), new DaoFrameUseTypeListTImpl());
			map.put(String.class.getName(), new DaoFrameUseTypeStringImpl());
			map.put(String[].class.getName(), new DaoFrameUseTypeStringsImpl());
			map.put(Integer.class.getName(), new DaoFrameUseTypeintImpl());
			map.put(Map.class.getName(), new DaoFrameUseTypeMapImpl());
		}
		return map.get(string);

	}
}
